<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属网关" prop="seriesId">
        <el-select v-model="queryParams.seriesId" placeholder="请选择所属网关"  @change="getDeviceTypeList">
          <el-option v-for="item in seriesList" :key="item.id" :value="item.id" :label="item.name" />
        </el-select>
      </el-form-item>
      <el-form-item label="设备类型" prop="deviceTypeId">
        <el-select v-model="queryParams.deviceTypeId" placeholder="请选择所属类型">
          <el-option v-for="item in deviceTypeList" :key="item.id" :value="item.id" :label="item.name" />
        </el-select>
      </el-form-item>
      <el-form-item label="分配企业" prop="companyId">
        <el-select v-model="queryParams.companyId" placeholder="请选择分配企业">
          <el-option v-for="item in companyList" :key="item.id" :value="item.id" :label="item.name" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['device:deviceInventory:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['device:deviceInventory:edit']"
        >修改</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport(scope.row)"
          v-hasPermi="['device:deviceInventory:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="deviceInventoryList" @selection-change="handleSelectionChange" >
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="批次号" align="left" prop="batchCode" width="280"/>
      <el-table-column label="设备类型" align="center" prop="typeName" />
      <el-table-column label="分配企业" align="center" prop="companyName" />
      <el-table-column label="入库数量" align="center" prop="warehousingNum" width="100"/>
      <el-table-column label="末尾设备号" align="center" prop="serialNum" width="150"/>
      <el-table-column label="后缀" align="center" prop="suffix"  width="150"/>
      <el-table-column label="激活数量" align="center" prop="activationTotal" width="150" />
      <el-table-column label="操作" align="center" width="320" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            type="text"
            icon="el-icon-view"
            size="mini"
            @click="getItemDetail(scope.row)"
          >查看</el-button>
          <el-button
            type="text"
            icon="el-icon-download"
            size="mini"
            @click="handleExport(scope.row)"
            v-hasPermi="['device:deviceInventory:export']"
          >导出</el-button>
          <el-link target="_blank" :href="downloadUrl+scope.row.firmwareId" :underline="false" style="margin: 0 10px;">
            <el-button
              type="text"
              icon="el-icon-folder-checked"
              size="mini"
              v-hasPermi="['device:deviceInventory:export']"
            >固件下载</el-button>
          </el-link>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-operation"
            @click.stop="handleUpdate(scope.row)"
            v-hasPermi="['device:deviceInventory:edit']"
          >追加编号</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click.stop="handleDelete(scope.row)"
            v-hasPermi="['device:deviceInventory:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备库存对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="设备类型" prop="deviceTypeId">
          <el-select v-model="form.deviceTypeId" placeholder="请选择所属类型" :disabled="form.id!=null">
            <el-option v-for="item in deviceTypeList" :key="item.id" :value="item.id" :label="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="分配到企业" prop="companyId">
          <el-select v-model="form.companyId" placeholder="请选择分配企业" :disabled="form.id!=null">
            <el-option v-for="item in companyList" :key="item.id" :value="item.id" :label="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="自编号" prop="suffix">
          {{ form.deviceTypeId ? deviceTypeList.filter( o => o.id == form.deviceTypeId).map( o => o.code + '_')[0] : ""}}
          <el-input v-model="form.suffix" placeholder="请输自编号" style="width:200px" :disabled="form.id!=null"/>
        </el-form-item>
        <el-form-item label="类型" prop="suffixType">
          <template>
            <el-radio v-model="form.suffixType" label="4G" :disabled="form.id!=null">4G</el-radio>
            <el-radio v-model="form.suffixType" label="ETH" :disabled="form.id!=null">以太网</el-radio>
          </template>
        </el-form-item>
        <el-form-item label="固件信息" prop="firmwareId">
          <template>
            <el-select v-model="form.firmwareId" placeholder="请选择固件" :disabled="form.id!=null">
              <el-option v-for="item in firmwareList" :key="item.fileId" :value="item.fileId" :label="item.name" />
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="入库数量" prop="warehousingNum">
          <el-input v-model="form.warehousingNum" placeholder="请输入入库数量" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 入库详情对话框 -->
    <div :class="['detail-popup',showDetail?'show':'']">
      <div class="popup-mask" @click="showDetail=false"></div>
      <div :class="['popup-main']">
        <el-table
          height="93%"
          :data="deviceInventorys"
          style="width: 100%;">
          <el-table-column
            label="MQTTID"
            prop="clientId"
            align="center"
            width="200">
          </el-table-column>
          <el-table-column
            label="设备编码"
            prop="deviceCode"
            align="center"
            width="180">
          </el-table-column>
          <el-table-column
            prop="coded"
            label="是否写码"
            align="center"
            :formatter="(row, column, cellValue, index) => cellValue===0 ? '否':'是'"
            width="100">
          </el-table-column>
          <el-table-column
            prop="codedFinishTime"
            label="完成写码时间"
            align="center"
            width="200">
          </el-table-column>
          <el-table-column
            prop="enabledSingle"
            label="一机一密"
            align="center"
            :formatter="(row, column, cellValue, index) => cellValue===0 ? '否':'是'"
            width="100">
          </el-table-column>
          <el-table-column
            prop="warehousingFlag"
            label="是否入库"
            align="center"
            :formatter="(row, column, cellValue, index) => cellValue===0 ? '否':'是'"
            width="100">
          </el-table-column>
          <el-table-column
            prop="warehousingTime"
            label="入库时间"
            align="center"
            width="200">
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="80">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click.stop="handleCodeUpdate(scope.row)"
                v-if="scope.row.warehousingFlag==0"
              >修改</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          style="margin-top: 30px;width: 100%;"
          v-show="inventoryTotal>0"
          :total="inventoryTotal"
          :pagerCount="5"
          layout="total, prev, pager, next"
          :page.sync="inventoryParams.pageNum"
          :limit.sync="inventoryParams.pageSize"
          @pagination="getInventoryData"
        />
      </div>
    </div>

    <!-- 修改入库编号对话框 -->
    <el-dialog :title="title" :visible.sync="codeOpen" width="800px" append-to-body>
      <el-form ref="form" :model="codeForm" :rules="rules" label-width="120px">
        <el-form-item label="MQTTID" prop="clientId">
          <el-input v-model="clientIdCopy" />
        </el-form-item>
        <el-form-item label="设备编码" prop="deviceCode">
          <el-input v-model="deviceCodeCopy" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitCodeForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDeviceInventory, getDeviceInventory, delDeviceInventory, addDeviceInventory, updateDeviceInventory,deviceInventoryCodes , updateDeviceInventoryCode, firmwareUpgradeList } from "@/api/device/deviceInventory";
import { optionSeries } from "@/api/device/series";
import { deviceTypeOptions } from "@/api/device/deviceType";
import { companyOptions } from "@/api/ztIot/company";
export default {
  name: "DeviceInventory",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      codeOpen:false,
      // 总条数
      total: 0,
      // 设备库存表格数据
      deviceInventoryList: [],
      seriesList:[],
      deviceTypeList:[],
      companyList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        seriesId: null,
        deviceTypeId: null,
        companyId: null,
        warehousingNum: null,
        serialNum: null,
        warehousingRate: null,
      },
      // 表单参数
      form: {},
      codeForm:{},
      // 表单校验
      rules: {
        seriesId: [
          { required: true, message: "系列ID不能为空", trigger: "blur" }
        ],
        deviceTypeId: [
          { required: true, message: "设备类型Id不能为空", trigger: "blur" }
        ],
        companyId: [
          { required: true, message: "分配到企业不能为空", trigger: "blur" }
        ],
        warehousingNum: [
          { required: true, message: "入库数量不能为空", trigger: "blur" }
        ],
        serialNum: [
          { required: true, message: "排序编号不能为空", trigger: "blur" }
        ],
        warehousingRate: [
          { required: true, message: "入库标识不能为空", trigger: "blur" }
        ],
        delFlag: [
          { required: true, message: "是否删除不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        firmwareId: [
          { required: true, message: "固件不能为空", trigger: "change" }
        ],
      },
      showDetail:false,
      inventoryId:'',
      inventoryParams:{
        pageNum: 1,
        pageSize: 23,
        inventoryId:''
      },
      inventoryTotal:0,
      deviceInventorys:[],
      firmwareList:[],
      downloadUrl:process.env.VUE_APP_BASE_API+"/system/files/anonymous/download/",
      deviceCodeCopy:'',
      clientIdCopy:'',
    };
  },
  created() {
    this.getList();
    this.getCompanyList();
    this.getDeviceTypeList();
    this.getfirmwareUpgradeList()
  },
  methods: {
    /** 查询设备库存列表 */
    getList() {
      this.loading = true;
      listDeviceInventory(this.queryParams).then(response => {
        this.deviceInventoryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //获取固件列表
    getfirmwareUpgradeList(){
      firmwareUpgradeList().then(res=>{
        this.firmwareList = res.data;
      })
    },
    //查询网关信息
    getSeriesList(){
      optionSeries().then( res => this.seriesList = res.data )
    },
    //设备类型列表
    getDeviceTypeList(){
      this.deviceTypeList = [];
      deviceTypeOptions().then( res => this.deviceTypeList = res.data )
    },
    //企业下拉列表
    getCompanyList(){
      companyOptions().then( res => this.companyList = res.data )
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.codeOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        seriesId: null,
        deviceTypeId: null,
        companyId: null,
        warehousingNum: null,
        serialNum: null,
        suffix:null,
        suffixType:'4G',
        warehousingRate: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.codeForm = {
        id: null,
        clientId:null,
        inventoryId: null,
        deviceCode: null,
        warehousingFlag: null,
        sort: null,
        warehousingTime:null
      };
      this.resetForm("form");
      this.resetForm("codeForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备库存";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getDeviceInventory(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改设备库存";
      });
    },
    handleCodeUpdate(row){
      this.reset();
      this.deviceCodeCopy = row.deviceCode;
      this.clientIdCopy = row.clientId;
      this.codeForm = row;
      this.codeOpen = true ;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.form.id){
            updateDeviceInventory(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            })
          }else{
            addDeviceInventory(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            })
          }
        }
      });
    },
    /** 提交按钮 */
    submitCodeForm() {
      this.codeForm.deviceCode = this.deviceCodeCopy;
      this.codeForm.clientId = this.clientIdCopy;
      updateDeviceInventoryCode(this.codeForm).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.codeOpen = false;
        this.getInventoryData();
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除设备库存编号为"' + ids + '"的数据项？').then(function() {
        return delDeviceInventory(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport(row) {
      this.download('device/deviceInventoryCodes/export', {
        ...{inventoryId:row.id}
      }, `${row.companyName}.xlsx`)
    },
    //
    getItemDetail(row){
      let id = row.id;
      this.inventoryParams.inventoryId = id;
      this.inventoryParams.pageNum = 1;
      this.getInventoryData()
    },
    getInventoryData(){
      deviceInventoryCodes(this.inventoryParams).then(res=>{
        this.deviceInventorys = res.rows;
        this.inventoryTotal = res.total;
        this.showDetail = true;
      })
    },
  }
};
</script>

<style lang="scss" scoped >
.detail-popup{
  position: fixed;
  top: 0;
  left: 0;
  z-index: 999;
  .popup-mask{
    position: fixed;
    top: 0;
    left: 0;
    opacity: 0;
    -webkit-transition: opacity 0.3s cubic-bezier(0.7, 0.3, 0.1, 1);
    transition: opacity 0.3s cubic-bezier(0.7, 0.3, 0.1, 1);
    background: rgba(0, 0, 0, 0.2);
    z-index: -1;
  }
  .popup-main{
    padding:50px 20px;
    width: 100%;
    max-width: 1200px;
    height: 100vh;
    position: fixed;
    top: 0;
    right: 0;
    -webkit-box-shadow: 0px 0px 15px 0px rgba(0, 0, 0, 0.05);
    box-shadow: 0px 0px 15px 0px rgba(0, 0, 0, 0.05);
    -webkit-transition: all 0.3s cubic-bezier(0.7, 0.3, 0.1, 1);
    transition: all 0.3s cubic-bezier(0.7, 0.3, 0.1, 1);
    background: #fff;
    z-index: 40000;
    transform: translate(100%);
    overflow: hidden;
  }
  &.show{
    transition: all 0.3s cubic-bezier(0.7, 0.3, 0.1, 1);
    .popup-mask{
      z-index: 20000;
      opacity: 1;
      width: 100%;
      height: 100%;
    }
    .popup-main{
      -webkit-transform: translate(0);
      transform: translate(0);
    }
  }
}
</style>
